'use strict';
/*
 * 莫凡服务端中间键：客户端请求状态和时间记录
 */
const path = require('path');
const util = require('util');

module.exports = () => {
  const skipExt = [ '.png', '.jpeg', '.jpg', '.ico', '.gif' ];
  return async function(ctx, next) {
    console.log("1111111111111111111111111111111111111111111111")
    const start = new Date().getTime();

    await next();
    
    const rs = Math.ceil(new Date().getTime() - start);
    ctx.set('X-Response-Time', rs);
    const ext = path.extname(ctx.url).toLocaleLowerCase();
    const isSkip = skipExt.indexOf(ext) !== -1 && ctx.status < 400;
    if (!isSkip) {
      const protocol = ctx.protocol.toUpperCase();
      const status = ctx.status;
      const length = ctx.length || '-';
      const referrer = ctx.get('referrer') || '-';
      const ua = ctx.get('user-agent') || '-';
      const serverTime = ctx.response.get('X-Response-Time') || '-';
      console.log(serverTime)
      const message = util.format('[morefun:访问日志] ', protocol, status, length, referrer, rs, serverTime, ua);
      ctx.logger.info(message);
    }
  };
};
